package com.gistone.commis.api.restController;

import com.gistone.commis.dto.EditorResult;
import com.gistone.commis.dto.FieldError;
import com.gistone.commis.entity.PersonCc;
import com.gistone.commis.mapper.PersonCcMapper;
import com.gistone.commis.util.DataTablePageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangfan on 2017/5/5.
 */
@RestController("apiPersonCcController")
@RequestMapping("api/personCc")
public class PersonCcController {

    private static final Logger logger = LoggerFactory.getLogger(PersonCcController.class);


    @Autowired
    private PersonCcMapper personCcMapper;




    /**
     * 获取所有社区
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/all")
    public List<PersonCc> loadAll() {
        return personCcMapper.findPersonCcs();
    }


    /**
     * 新建y用户信息
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public EditorResult<PersonCc> create(HttpServletRequest request, HttpServletResponse response) {


        PersonCc personCc = new PersonCc();
        EditorResult<PersonCc> personCcEditorResult = new EditorResult<>();
        List<FieldError> fieldErrorList = new ArrayList<>();
//        house.setHouseId(houseId);
        getPersonCc(request, "data[0][", personCc,fieldErrorList);


        if(fieldErrorList.size()>0){
            logger.error("字段格式错误");
            personCcEditorResult.setFieldErrors(fieldErrorList);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return personCcEditorResult;
        }
        if (personCcMapper.insertSelective(personCc)> 0) {
            List<PersonCc> data = new ArrayList<>();
            data.add(personCcMapper.selectByPrimaryKey(personCc.getCcId()))	;
            personCcEditorResult.setData(data);
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }


        return personCcEditorResult;
    }

    /**
     * 批量修改房屋信息， id以,号分割
     *
     * @param houseIdStr
     * @param request
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/edit")
    public Object edit(@RequestParam("id") String houseIdStr, HttpServletRequest request, HttpServletResponse response) {
        String[] arr = houseIdStr.split(",");
        EditorResult<PersonCc> personCcEditorResult = new EditorResult<>();

        List<PersonCc> data =new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            int personCcId = Integer.valueOf(arr[i]);

            System.out.println(personCcId);
            PersonCc personCc = new PersonCc();

            personCc.setCcId(personCcId);
            List<FieldError> fieldErrorList = new ArrayList<>();
            getPersonCc(request, "data[" + personCcId + "][", personCc , fieldErrorList );
            if(fieldErrorList.size()>0){
                logger.error("字段错误");
                personCcEditorResult.setFieldErrors(fieldErrorList);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return personCcEditorResult;
            }
            if (personCcMapper.updateByPrimaryKeySelective(personCc) > 0) {
                data.add(personCcMapper.selectByPrimaryKey(personCcId));


            }else{
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }


        }

        personCcEditorResult.setData(data);
        return personCcEditorResult;


    }


    /**
     * 用户删除
     * 通过房屋ID批量删除房屋信息， id以,号分割
     *
     * @param personCcIdStr
     * @param request
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.DELETE, value = "/remove")
    public Object remove(@RequestParam("id") String personCcIdStr, HttpServletRequest request, HttpServletResponse response) {
        String[] arr = personCcIdStr.split(",");
        EditorResult<PersonCc> personCcEditorResult = new EditorResult<>();
        for (int i = 0; i < arr.length; i++) {
            int personCcId = Integer.valueOf(arr[i]);
            if (personCcMapper.deleteByPrimaryKey(personCcId) > 0) {
                System.out.println("删除" + personCcId + "成功！");


            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
        return personCcEditorResult;


    }

    /**
     * dataTables 表单数据返回
     *
     * @param request
     * @return
     */

    @RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
    public DataTablePageUtil<PersonCc> pageDatatables(HttpServletRequest request, PersonCc personCc) {
//		HttpSession httpSession = request.getSession();
//		PersonCc personCc = (PersonCc) httpSession.getAttribute("personCcInfo");
//		logger.info("用户信息：" + personCc.toString());
//		int community_id = personCc.getCommunity().getCommunityId();
//		personCc.setCommunityId(community_id);
        System.out.println(personCc.toString());

//        List<Community> communities =communityMapper.findCommunitys();
//        Options os =new Options();
//        List<Option> optionList =new ArrayList<>();
//        for (Community community : communities) {
//
//            Option option =new Option();
//            option.setLabel(community.getCommunityName());
//            option.setValue(community.getCommunityId());
//            optionList.add(option);
//
//
//        }
//        os.setCommunityId(optionList);
//        List<Depart> departs =departMapper.findDeparts();
//        optionList =new ArrayList<>();
//        for (Depart depart : departs) {
//
//            Option option =new Option();
//            option.setLabel(depart.getDepartName());
//            option.setValue(depart.getDepartId());
//            optionList.add(option);
//
//
//        }
//
//        os.setDepartId(optionList);



        DataTablePageUtil<PersonCc> dataTable = new DataTablePageUtil<>(request);

        PageHelper.startPage(dataTable.getPage_num(), dataTable.getPage_size());
        List<PersonCc> list = personCcMapper.selectSelective(personCc);
        PageInfo<PersonCc> pageInfo =new PageInfo<>(list);
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
//        dataTable.setOptions(os);
        dataTable.setRecordsTotal((int)pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面


        return dataTable;

    }

    private void getPersonCc(HttpServletRequest request, String prefix, PersonCc personCc,List<FieldError> fieldErrorList ) {



        if(request.getParameter(prefix + "ccName]").isEmpty()){
            logger.error("格式不正确");
            FieldError fieldError =new FieldError("ccName","分档名称不能为空");
            fieldErrorList.add(fieldError);
        }else {
            personCc.setCcName(request.getParameter(prefix + "ccName]"));
        }

        try {
            personCc.setCcWage(Double.valueOf(request.getParameter(prefix + "ccWage]")));
        } catch (NumberFormatException e) {
            logger.error("数量格式不正确，必须为整形数字");
            FieldError fieldError =new FieldError("ccWage","格式不正确，必须为整形数字");
            fieldErrorList.add(fieldError);
        }






    }



}
